<template>
  <div class="app-container">
    <el-form
      :model="queryParams"
      ref="queryForm"
      size="small"
      :inline="true"
      v-show="showSearch"
      label-width="68px"
    >
      <el-form-item label="项目编号" prop="projectNumber">
        <el-input
          v-model="queryParams.projectNumber"
          placeholder="请输入项目编号"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="培训项目" prop="trainingProject">
        <el-input
          v-model="queryParams.trainingProject"
          placeholder="请输入培训项目"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item>
        <el-button
          type="primary"
          icon="el-icon-search"
          size="mini"
          @click="handleQuery"
          >搜索</el-button
        >
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery"
          >重置</el-button
        >
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          icon="el-icon-plus"
          size="mini"
          @click="handleAdd"
          v-hasPermi="['system:educate:add']"
          >新增</el-button
        >
      </el-col>

      <el-col :span="1.5">
        <el-button
          type="danger"
          plain
          icon="el-icon-delete"
          size="mini"
          :disabled="multiple"
          @click="handleDelete"
          v-hasPermi="['system:educate:remove']"
          >删除</el-button
        >
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="warning"
          plain
          icon="el-icon-download"
          size="mini"
          @click="handleExport"
          v-hasPermi="['system:educate:export']"
          >导出</el-button
        >
      </el-col>
      <right-toolbar
        :showSearch.sync="showSearch"
        @queryTable="getList"
      ></right-toolbar>
    </el-row>

    <el-table
      v-loading="loading"
      :data="educateList"
      @selection-change="handleSelectionChange"
    >
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column label="序号" align="center" prop="id">
      <template #default="{ $index }">
        {{ $index + 1 }} <!-- 动态生成序号 -->
      </template>
    </el-table-column>
      <el-table-column label="项目编号" align="center" prop="projectNumber" />
      <el-table-column label="培训项目" align="center" prop="trainingProject" />
      <el-table-column label="计划类别" align="center" prop="planType" />
      <el-table-column
        label="组织部门/科室"
        align="center"
        prop="organizingDepartment"
        width="120"
      />
      <el-table-column
        label="实施部门/科室"
        align="center"
        prop="implementingDepartment"
        width="120"
      />
      <el-table-column label="培训对象" align="center" prop="trainingTarget" />

      <el-table-column
        label="培训时间"
        align="center"
        prop="trainingTime"
        width="160"
      >
        <!-- <template slot-scope="scope">
          <span>{{ parseTime(scope.row.trainingTime, "{y}-{m}-{d}") }}</span>
        </template> -->
      </el-table-column>

      <el-table-column label="培训方式" align="center" prop="trainingMethod" />
      <el-table-column
        label="培训分类"
        align="center"
        prop="trainingClassification"
      />

      <el-table-column
        label="创建时间"
        align="center"
        prop="creationTime"
        width="150"
      >
        <template slot-scope="scope">
          <span>{{
            parseTime(scope.row.creationTime, "{y}-{m}-{d}-{h}:{m}:{s}")
          }}</span>
        </template>
      </el-table-column>

      <el-table-column label="执行情况" align="center" prop="executionStatus">
      <template #default="{ row }">
        <span :style="getStatusStyle(row.executionStatus)">
          {{ row.executionStatus }}
        </span>
      </template>
    </el-table-column>

      <el-table-column
        label="操作"
        align="center"
        class-name="small-padding fixed-width"
      >
        <template slot-scope="scope">
          <el-button
            size="mini"
            type="text"
            @click="handleRequire(scope.row)"
            v-hasPermi="['system:educate:query']"
            >详情</el-button
          >

          <el-button
            size="mini"
            type="text"
            @click="handleUpdate(scope.row)"
            v-hasPermi="['system:educate:edit']"
            >修改</el-button
          >
          <el-button
          size="mini"
          type="text"
          style="color: red"
          @click="handleDelete(scope.row)"
          v-hasPermi="['system:educate:remove']"
        >
          删除
        </el-button>
        </template>
      </el-table-column>
    </el-table>

    <pagination
      v-show="total > 0"
      :total="total"
      :page.sync="queryParams.pageNum"
      :limit.sync="queryParams.pageSize"
      @pagination="getList"
    />

    <!-- 添加或修改培训对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="500px" append-to-body>
      <el-form ref="form" :model="form" :rules="rules" label-width="80px">
        <el-form-item label="项目编号" prop="projectNumber">
          <el-input v-model="form.projectNumber" placeholder="请输入项目编号" />
        </el-form-item>
        <el-form-item label="培训项目" prop="trainingProject">
          <el-input
            v-model="form.trainingProject"
            placeholder="请输入培训项目"
          />
        </el-form-item>
        <el-form-item label="计划类别" prop="planType">
          <el-input v-model="form.planType" placeholder="请输入计划类别" />
        </el-form-item>
        <el-form-item label="培训时间" prop="trainingTime">
          <el-date-picker
            clearable
            v-model="form.trainingTime"
            type="date"
            value-format="yyyy-MM-dd"
            placeholder="请选择培训时间"
          >
          </el-date-picker>
        </el-form-item>
        <el-form-item label="组织部门科室" prop="organizingDepartment">
          <el-input
            v-model="form.organizingDepartment"
            placeholder="请输入组织部门科室"
          />
        </el-form-item>
        <el-form-item label="实施部门科室" prop="implementingDepartment">
          <el-input
            v-model="form.implementingDepartment"
            placeholder="请输入实施部门科室"
          />
        </el-form-item>
        <el-form-item label="培训对象" prop="trainingTarget">
          <el-input
            v-model="form.trainingTarget"
            placeholder="请输入培训对象"
          />
        </el-form-item>
        <el-form-item label="计划参训人数(人)" prop="plannedParticipants">
          <el-input
            v-model="form.plannedParticipants"
            placeholder="请输入计划参训人数(人)"
          />
        </el-form-item>
        <el-form-item label="培训地点" prop="trainingLocation">
          <el-input
            v-model="form.trainingLocation"
            placeholder="请输入培训地点"
          />
        </el-form-item>
        <el-form-item label="培训方式" prop="trainingMethod">
          <el-input
            v-model="form.trainingMethod"
            placeholder="请输入培训方式"
          />
        </el-form-item>
        <el-form-item label="培训分类" prop="trainingClassification">
          <el-input
            v-model="form.trainingClassification"
            placeholder="请输入培训分类"
          />
        </el-form-item>
        <el-form-item label="培训课时(小时)" prop="trainingHours">
          <el-input
            v-model="form.trainingHours"
            placeholder="请输入培训课时(小时)"
          />
        </el-form-item>
        <el-form-item label="培训师资" prop="training师资">
          <el-input v-model="form.training师资" placeholder="请输入培训师资" />
        </el-form-item>
        <el-form-item label="培训方向" prop="trainingDirection">
          <el-input
            v-model="form.trainingDirection"
            placeholder="请输入培训方向"
          />
        </el-form-item>
        <el-form-item label="培训类别" prop="trainingCategory">
          <el-input
            v-model="form.trainingCategory"
            placeholder="请输入培训类别"
          />
        </el-form-item>
        <el-form-item label="备注" prop="remarks">
          <el-input
            v-model="form.remarks"
            type="textarea"
            placeholder="请输入内容"
          />
        </el-form-item>
        <el-form-item label="差旅费(元)" prop="travelExpenses">
          <el-input
            v-model="form.travelExpenses"
            placeholder="请输入差旅费(元)"
          />
        </el-form-item>
        <el-form-item label="培训费(元)" prop="trainingFees">
          <el-input
            v-model="form.trainingFees"
            placeholder="请输入培训费(元)"
          />
        </el-form-item>
        <el-form-item label="总预算(元)" prop="totalBudget">
          <el-input v-model="form.totalBudget" placeholder="请输入总预算(元)" />
        </el-form-item>
        <el-form-item
          label="培训材料，可记录上传文件相关信息"
          prop="trainingMaterials"
        >
          <el-input
            v-model="form.trainingMaterials"
            type="textarea"
            placeholder="请输入内容"
          />
        </el-form-item>
        <el-form-item label="创建时间" prop="creationTime">
          <el-date-picker
            clearable
            v-model="form.creationTime"
            type="date"
            value-format="yyyy-MM-dd"
            placeholder="请选择创建时间"
          >
          </el-date-picker>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>

  </div>
</template>

<script>
// import { listEducate, getEducate, delEducate, addEducate, updateEducate,myGetEducate } from "@/api/system/educate";
import { WebSocketClient } from "@/utils/websocket"; // 导入 WebSocket 工具类
import SockJS from "sockjs-client";
import Stomp from "stompjs";

import {
  listEducate,
  getEducate,
  delEducate,
  addEducate,
  updateEducate,
  myGetEducate,
} from "@/api/system/educate";
import { proxyRefs } from "vue";

export default {
  components: {},

  name: "Educate",
  data() {
    return {
      
      ids: [], // 选中的 id 列表
      tableData: [
        { executionStatus: '未完成' },
        { executionStatus: '完成' },
        // 其他数据
      ],
      socket: null, // WebSocket 实例
      messages: [], // 存储收到的消息
      //新增
      isShow: false,
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 培训表格数据
      educateList: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        projectNumber: null,
        trainingProject: null,
      },
      // 表单参数
      form: {},
      // 表单校验
      rules: {
        projectNumber: [
          { required: true, message: "项目编号不能为空", trigger: "blur" },
        ],
        trainingProject: [
          { required: true, message: "培训项目不能为空", trigger: "blur" },
        ],
        planType: [
          { required: true, message: "计划类别不能为空", trigger: "change" },
        ],
        trainingTime: [
          { required: true, message: "培训时间不能为空", trigger: "blur" },
        ],
        organizingDepartment: [
          { required: true, message: "组织部门科室不能为空", trigger: "blur" },
        ],
        implementingDepartment: [
          { required: true, message: "实施部门科室不能为空", trigger: "blur" },
        ],
        trainingTarget: [
          { required: true, message: "培训对象不能为空", trigger: "blur" },
        ],
        plannedParticipants: [
          {
            required: true,
            message: "计划参训人数(人)不能为空",
            trigger: "blur",
          },
        ],
        trainingLocation: [
          { required: true, message: "培训地点不能为空", trigger: "blur" },
        ],
        trainingMethod: [
          { required: true, message: "培训方式不能为空", trigger: "blur" },
        ],
        trainingClassification: [
          { required: true, message: "培训分类不能为空", trigger: "blur" },
        ],
        trainingHours: [
          {
            required: true,
            message: "培训课时(小时)不能为空",
            trigger: "blur",
          },
        ],
        training师资: [
          { required: true, message: "培训师资不能为空", trigger: "blur" },
        ],
      },
      wsClient: null, // WebSocket 客户端实例
    };
  },
  created() {
    this.getList();
  },
  mounted() {
    this.initWebSocket(); // 初始化 WebSocket 连接
  },
  beforeUnmount() {
    if (this.wsClient) {
      this.wsClient.disconnect(); // 组件销毁时断开连接
    }
  },
  methods: {
    // 初始化 WebSocket 连接
    initWebSocket() {
      const wsUrl = "ws://localhost:8080/ws/plan"; // WebSocket 地址
      this.socket = new WebSocket(wsUrl);

      // 监听连接成功
      this.socket.onopen = () => {
        console.log("WebSocket 连接成功");
      };

      // 监听收到消息
      this.socket.onmessage = (event) => {
        const message = event.data;
        console.log("收到消息:", message);
        this.messages.push(message); // 将消息存储到数组中
      };

      // 监听错误
      this.socket.onerror = (error) => {
        console.error("WebSocket 错误:", error);
      };
    },

    // 处理收到的消息
    handleMessage(message) {
      console.log("Received message:", message);
      this.showNotification(message); // 弹出提示小窗口
    },

    // 显示提示小窗口
    showNotification(message) {
      ElMessage({
        message: message,
        // type: 'info', // 消息类型：success/warning/info/error
        duration: 5000, // 显示时长（毫秒）
        showClose: true, // 显示关闭按钮
      });
    },
    /** 查询培训列表 */
    getList() {
      this.loading = true;
      listEducate(this.queryParams).then((response) => {
        this.educateList = response.rows;
        this.total = response.total;
        this.loading = false;
      });
    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
    },
    // 表单重置
    reset() {
      this.form = {
        id: null,
        projectNumber: null,
        trainingProject: null,
        planType: null,
        trainingTime: null,
        organizingDepartment: null,
        implementingDepartment: null,
        trainingTarget: null,
        plannedParticipants: null,
        trainingLocation: null,
        trainingMethod: null,
        trainingClassification: null,
        trainingHours: null,
        training师资: null,
        trainingDirection: null,
        trainingCategory: null,
        remarks: null,
        travelExpenses: null,
        trainingFees: null,
        totalBudget: null,
        trainingMaterials: null,
        creationTime: null,
        executionStatus: null,
      };
      this.resetForm("form");
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm");
      this.handleQuery();
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map((item) => item.id);
      this.single = selection.length !== 1;
      this.multiple = !selection.length;
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset();
      // this.open = true;
      this.title = "添加培训";
      this.$router.push("/educateAdd");
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset();
      const id = row.id || this.ids;
      getEducate(id).then((response) => {
        this.form = response.data;
        this.open = true;
        this.title = "修改培训";
      });
    },

    /** 提交按钮 */
    submitForm() {
      this.$refs["form"].validate((valid) => {
        if (valid) {
          if (this.form.id != null) {
            updateEducate(this.form).then((response) => {
              this.$modal.msgSuccess("修改成功");
              this.open = false;
              this.getList();
            });
          } else {
            addEducate(this.form).then((response) => {
              this.$modal.msgSuccess("新增成功");
              this.open = false;
              this.getList();
            });
          }
        }
      });
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const ids = row.id || this.ids;
      this.$modal
        .confirm('是否确认删除培训编号为"' + ids + '"的数据项？')
        .then(() => {
          return delEducate(ids); // 调用删除接口
        })
        .then(() => {
          this.getList(); // 删除成功后重新获取数据
          this.$modal.msgSuccess("删除成功");
        })
        .catch(() => {});
    },
  
    /**详情按钮操作*/
    handleRequire(row) {
      const id = row.id || this.ids;
      myGetEducate(id).then((response) => {
        this.form = response.data;
        this.open = true;
        this.title = "培训详情";
        // this.$router.push("/educateRequire");
        // 通过 params 传递数据
        this.$router.push({
          name: "educateRequire",
          params: {
            formData: this.form, // 传递 form 数据
          },
        });
      });
    },

    /** 导出按钮操作 */
    handleExport() {
      this.download(
        "system/educate/export",
        {
          ...this.queryParams,
        },
        `educate_${new Date().getTime()}.xlsx`
      );
    },
    getStatusStyle(status) {
      if (status === '未完成') {
        return { color: 'orange' }; // 未完成时字体颜色为橙色
      } else if (status === '完成') {
        return { color: 'green' }; // 完成时字体颜色为绿色
      }
      return {}; // 默认样式
    },
  },
};
</script>
